/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useCallback } from 'react';
import { Progress, Modal, Button, Row, Col } from 'antd';
import styles from './index.less';

const ProgressModal = (props) => {
  const { children, onDone, status, placeholder, speed, footer } = props;
  const [visible, updateVisible] = useState(false);
  const [percent, updatePercent] = useState(0);
  const isComplete = status === 'complete';
  const isActive = status === 'active';

  let progressTimer;
  useEffect(() => {
    if (!status) return;
    let current = 0;
    if (isActive) {
      // 活动状态
      progressTimer = setInterval(() => {
        current++;
        if (current >= 99) {
          current = 99;
          clearInterval(progressTimer);
        }
        updatePercent(current);
      }, speed);
      updateVisible(isActive);
    } else if (isComplete) {
      // 完成
      updatePercent(100);
      if (!children) {
        updateVisible(false);
      }
    } else {
      // 中断
      updateVisible(false);
    }

    return () => {
      updatePercent(0);
      clearInterval(progressTimer);
    };
  }, [status]);

  // 关闭弹窗
  const handleCancel = useCallback(() => {
    updateVisible(false);
    onDone();
  }, []);

  return (
    <Modal
      title={isComplete ? '温馨提示' : ''}
      visible={visible}
      closable={false}
      footer={null}
      maskClosable={false}
      width={500}
      centered
      footer={
        isComplete ? (
          footer ? (
            <Row type="flex" justify="space-around">
              {
                footer.map(element => {
                  return (
                    <Col key={element.key}>
                      {
                        element.key == "cancel" ?
                          React.cloneElement(element, {
                            onClick: handleCancel
                          }) : element
                      }
                    </Col>
                  )
                })
              }
            </Row>
          ) : (
              <Button type="primary" onClick={handleCancel}>
                确定
              </Button>
            )
        ) : null
      }
      onCancel={handleCancel}
    >
      <div className={styles.content}>
        {isComplete && children ? (
          <div className={styles.complete}>{children}</div>
        ) : (
            <div className={styles.active}>
              <h3>正在{placeholder}，请勿关闭该页面</h3>
              <p>处理进度：{percent}%.....</p>
              <Progress strokeWidth={15} percent={percent} showInfo={false} status={status} />
            </div>
          )}
      </div>
    </Modal>
  );
};

ProgressModal.defaultProps = {
  speed: 100,
  status: '',
  extraButtonText: '',
  onClickExtraButton: () => { },
  placeholder: '导入数据',
  onDone: () => { },
};

export default ProgressModal;